package cc.atliberty.session;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet("/RegisterServlet")
public class RegisterServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String clientCode = request.getParameter("client_code");
        String serverCode = request.getSession(false).getAttribute("server_code").toString();

        Connection conn = null;
        PreparedStatement ps = null;

        try {
            conn = DBUtil.getConnection();
            String sql = "insert into t_user(username, password) values(?,?)";
            ps = conn.prepareStatement(sql);
            ps.setString(1, username);
            ps.setString(2,password);
            if (clientCode.equals(serverCode)){
                int count = ps.executeUpdate();
                if (count == 1){
                    out.print("注册成功");
                }else {
                    out.print("注册失败");
                }
            }else {
                out.print("注册失败");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn,ps,null);
        }
    }
}
